<!-- imageFile 是声明到全局的 -->
{% macro img(src, width, height, blobEventName, clickEventName) %}
<script>
  function dataURLtoBlob(dataurl) {
    var arr = dataurl.split(","),
      mime = arr[0].match(/:(.*?);/)[1],
      bstr = atob(arr[1]),
      n = bstr.length,
      u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], { type: mime });
  }
  function loadBase64(img, prefix = true) {
    return new Promise((resolve) => {
      let image = new Image();
      if (prefix) {
        image.src = `data:image/gif;base64,${img}`;
      } else {
        image.src = img;
      }
      image.onload = function () {
        resolve(image);
      };
    });
  }
</script>
<input type="file" id="upload-image-input" style="display: none" />
<div class="image-box">
  <div class="image-wrap">
    <img style="width: 100%; cursor: pointer; border-radius: 50%; box-shadow: 0 0 0 1px rgb(27 31 36 / 15%)" id="clip-image" src="{{ src }}" alt=""
      class="img-thumbnail" />
  </div>
</div>
<canvas id="clip-canvas" width="{{ width }}" height="{{ height }}" style="display: none">
</canvas>
<script>
  !(function () {
    var input = $("#upload-image-input");
    input.on("change", function (e) {
      var file = this.files[0];
      var url = URL.createObjectURL(file);
      var image = new Image
      image.src = url
      image.onload = function () {
        $('#clip-canvas')[0].getContext('2d').drawImage(image, 0, 0, {{ width }}, {{ height }});
        var clip = $('#clip-canvas')[0].toDataURL("image/png");
        loadBase64(clip, false).then((res) => {
        var imageFile = dataURLtoBlob(res.src);
        var event = new CustomEvent("{{ blobEventName }}", {
          detail: {
            blob: imageFile,
          }
        });
        window.dispatchEvent(event)
        $("#clip-image").attr('src', res.src)
      });
    };
      
    });
  {% if clickEventName === "" %}
  $("#clip-image").on("click", function () {
    input.click();
  });
  {% else %}
  window.addEventListener('{{ clickEventName }}', function () {
    input.click()
  })
  {% endif %}
  }) ();
</script>
{% endmacro %}